from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
import jwt, datetime
from .sers import *
from HYDPro_2002a.settings import SECRET_KEY, EMAIL_HOST_USER
from django.core.mail import send_mail
from django.contrib.auth.hashers import check_password, make_password


class RegisterView(APIView):

    def post(self, request):
        # 注册

        # 创建序列化器
        ser = RegisterSer(data=request.data)

        # 验证数据
        if ser.is_valid():
            # 保存并返回这个新注册的用户实例
            user = ser.save()

            # 发送一个激活邮件 ，让用户去激活

            send_mail(subject="白天工作室激活邮件", message="", from_email=EMAIL_HOST_USER,
                      recipient_list=[request.data.get("email")],
                      html_message="恭喜您，已经注册我们的账号，给你10块请<a href='http://127.0.0.1:8000/active?id=%d'>买奶茶喝</a>! "
                                   "<a href='http://127.0.0.1:8080/#/login'>跳到vue</a>" % user.id)
            return Response({"msg": "注册成功", "status": 200})
        else:
            print(ser.errors)
            return Response({"msg": "注册失败", "status": 400, "errors": ser.errors})


class UserView(APIView):

    def get(self, request):
        # 获取传递来的用户名
        username = request.GET.get("username")
        # 到数据库查询传递来的用户名是否已存在
        if User.objects.filter(username=username):
            return Response({"msg": "该用户名已存在", "status": 400})

        return Response({"msg": "用户名可用", "status": 200})


def active_user(request):
    # 激活的本意就是修改用户的状态
    id = request.GET.get("id")
    User.objects.filter(id=id).update(level=2)
    return HttpResponse("激活成功")


class LoginView(APIView):

    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        # 验证
        user = User.objects.filter(username=username).first()
        print("user.password=", user.password)

        if user and check_password(password, user.password):
            # 登录成功 生成一个令牌
            payload = {
                # exp 表示到期时间
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=3),
                'uid': user.id
            }
            key = jwt.encode(payload, SECRET_KEY)
            return Response({"msg": "登录成功", "status": 200, "token": key})

        return Response({"msg": "登录失败", "status": 400})


class TestTokenView(APIView):

    def get(self, request):
        token = request.GET.get("token")
        print(token)

        # 验证令牌
        try:
            data = jwt.decode(token, SECRET_KEY, verify=True)
        except Exception as e:
            print(e)
            return Response({"msg": "没有登录或登录状态已失效，请重新登录"})

        uid = data.get("uid")
        user = User.objects.get(id=uid)

        return Response({"msg": "%s已登录" % user.username})

    def post(self, request):
        resp = Response({"msg": "添加成功"})
        return resp
